<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" v-show="showSearch" label-width="68px">
      <el-form-item label="医院名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入医院名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区域" prop="provinceCode">
        <el-select v-model="queryParams.provinceCode" placeholder="请选择省" @change="initCity" style="width: 150px">
          <el-option
            v-for="item in provinceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-select v-model="queryParams.cityCode" @change="initArea" placeholder="请选择市"
                   style="margin-left: 5px;width: 150px"
        >
          <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-select v-model="queryParams.districtCode" placeholder="请选择区" @change="chooseArea"
                   style="margin-left: 5px;width: 150px"
        >
          <el-option
            v-for="item in districtList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="等级" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择医院等级" size="small">
          <el-option
            v-for="dict in dict.type.biz_hospital_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="queryParams.status" @change="handleQuery">
          <el-radio-button :label="undefined">全部</el-radio-button>
          <el-radio-button label="active">启用</el-radio-button>
          <el-radio-button label="inactive">禁用</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:hospital:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:hospital:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-circle-check"
          size="mini"
          :disabled="multiple"
          @click="handleBatchChangeStatus('active')"
          v-hasPermi="['biz:hospital:changeStatusBatch']"
        >批量启用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-circle-close"
          size="mini"
          :disabled="multiple"
          @click="handleBatchChangeStatus('inactive')"
          v-hasPermi="['biz:hospital:changeStatusBatch']"
        >批量禁用
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hospitalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="医院名称" align="center" prop="name">
        <template slot-scope="scope">
          <span style="cursor: pointer;color: #1c84c6;" @click="goDetail(scope.row)"
                v-hasPermi="['biz:hospital:query']"
          >{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医院Logo" align="center" prop="logo">
        <template slot-scope="scope">
          <el-image :src="scope.row.logo" style="width: 80px; height: 60px;cursor: pointer"
                    @click="view(scope.row.logo)"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="医院等级" align="center" prop="level">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_hospital_level" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column label="区域" align="center" prop="province">
        <template slot-scope="scope">
          {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district }}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="address"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 'active'" style="color: green">启用</span>
          <span v-if="scope.row.status === 'inactive'" style="color: red">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.status==='inactive'"
            size="mini"
            type="text"
            icon="el-icon-check"
            style="color: #4AB7BD"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['biz:hospital:changeStatus']"
          >启用
          </el-button>
          <el-button
            v-show="scope.row.status==='active'"
            size="mini"
            type="text"
            icon="el-icon-close"
            style="color: #E65D6E"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['biz:hospital:changeStatus']"
          >禁用
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:hospital:edit']"
          >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医院对话框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      size="50%"
      :show-close="true"
      :wrapperClosable="false"
      :before-close="closeDrawer"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-left: 20px">
        <el-form-item label="医院logo" prop="logo">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            name="multipartFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logo" :src="form.logo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" style="color: red">推荐上传jpg、png、jpeg文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="医院名称" prop="name">
          <el-input v-model="form.name" maxlength="100" placeholder="请输入医院名称" style="width: 70%"/>
        </el-form-item>
        <el-form-item label="医院等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择医院等级" style="width: 70%;">
            <el-option
              v-for="dict in dict.type.biz_hospital_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医院性质" prop="nature">
          <el-input v-model="form.nature" maxlength="10" placeholder="请输入医院性质" style="width: 70%;"/>
        </el-form-item>
        <el-form-item label="医院特色" prop="feature">
          <el-input v-model="form.feature" maxlength="30" placeholder="请输入特色" style="width: 70%;"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" maxlength="20" placeholder="请输入联系电话" style="width: 70%;"/>
        </el-form-item>
        <el-form-item label="医院传真" prop="fax">
          <el-input v-model="form.fax" maxlength="50" placeholder="请输入传真" style="width: 70%;"/>
        </el-form-item>
        <el-form-item prop="imageArr" label="轮播图片">
          <el-upload
            :action="upload.url"
            name = "multipartFile"
            multiple
            :limit="uploadSize"
            list-type="picture-card"
            :file-list="fileList"
            :on-exceed="handleUploadExceed"
            :with-credentials='true'
            :on-remove="handleRemove"
            :on-error="handleError"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="省市区" prop="provinceCode">
          <el-select v-model="form.provinceCode" placeholder="请选择省" @change="initCity" style="width: 185px">
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-select v-model="form.cityCode" @change="initArea" placeholder="请选择市"
                     style="margin-left: 30px;width: 185px"
          >
            <el-option
              v-for="item in cityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-select v-model="form.districtCode" placeholder="请选择区" @change="chooseArea"
                     style="margin-left: 30px;width: 185px"
          >
            <el-option
              v-for="item in districtList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" maxlength="255" placeholder="请输入详细地址" style="width: 70%;"/>
        </el-form-item>
        <div class="split-box" style="display: flex;align-items: center;">
          <el-form-item prop="longitude" label="经度">
            <el-input disabled v-model="form.longitude" placeholder="请搜索地址查询经度"/>
          </el-form-item>
          <el-form-item prop="latitude" label="纬度">
            <el-input disabled v-model="form.latitude" placeholder="请搜索地址查询纬度"/>
          </el-form-item>
        </div>
        <el-form-item label="" >
          <el-amap-search-box class="search-box" :default="defaultValue"  :search-option="searchOption" :on-search-result="onSearchResult" style="margin-bottom: 10px;width: 80%">
          </el-amap-search-box>
          <div style="width: 1000px;height: 400px">
            <el-amap ref="map" vid="amapDemo" :events="events" :center="center" :zoom="zoom" class="amap-demo">
              <el-amap-marker :position="center" key="100"></el-amap-marker>
            </el-amap>
          </div>
        </el-form-item>
        <el-form-item label="成立时间" prop="setUpDate">
          <el-date-picker clearable size="small" style="width: 70%;"
                          v-model="form.setUpDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择成立时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio-button label="active">启用</el-radio-button>
            <el-radio-button label="inactive">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" maxlength="255" placeholder="请输入备注" style="width: 70%;"/>
        </el-form-item>
        <el-form-item label="医院简介" prop="description">
          <!--          <UEditor  :editor-content="form.description"  @updateContent="val => {this.form.description = val;}"/>-->
          <Editor v-model="form.description" style="height: 300px;width: 95%"/>
        </el-form-item>
      </el-form>
      <!--      <div slot="footer" class="dialog-footer">-->
      <!--        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>-->
      <!--        <el-button @click="cancel">取 消</el-button>-->
      <!--      </div>-->
      <div style="text-align: center;margin-top: 70px">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>

    <el-drawer
      title="医院详情"
      :visible.sync="drawer"
      size="50%"
      :show-close="true"
      :wrapperClosable="false"
      append-to-body
    >
      <div class="imageDiv">
        <el-image :src="form.logo" style="height: 100px"></el-image>
      </div>
      <div style="height:100px;width:300px;" class="dd">
        <h3 style="margin-left: 17px;margin-top: 5px">{{ form.name }}</h3>
        <!--等级-->
        <el-tag
          v-for="dict in dict.type.biz_hospital_level"
          v-if="dict.value === form.level"
          :key="dict.label"
          type="success"
          class="level"
          effect="dark"
        >
          {{ dict.label }}
        </el-tag>
        <!--特色-->
<!--        <el-tag-->
<!--          type="danger"-->
<!--          class="level"-->
<!--          effect="dark"-->
<!--        >-->
<!--          {{ form.nature }}-->
<!--        </el-tag>-->
        <el-button type="danger" style="margin-left: 20px"> {{ form.nature }}</el-button>
      </div>
      <div style="height: 100px">
        <span v-if="form.status === 'active'" style="color: green">在用</span>
        <span v-if="form.status === 'inactive'" style="color:red;">禁用</span>
        <div>
          <el-button
            type="primary"
            style="margin-left: 200px"
            @click="handleEdit"
            v-hasPermi="['biz:hospital:edit']"
          >编辑
          </el-button>
          <el-button
            type="success"
            style="margin-left: 20px"
            v-if="form.status === 'inactive'"
            @click="handleUpdateStatus(form.id,form.status)"
            v-hasPermi="['biz:hospital:changeStatus']"
          >启用
          </el-button>
          <el-button
            type="danger"
            style="margin-left: 20px"
            @click="handleUpdateStatus(form.id,form.status)"
            v-if="form.status === 'active'"
            v-hasPermi="['biz:hospital:changeStatus']"
          >禁用
          </el-button>
        </div>

      </div>

      <div style="margin: 20px 20px">
        <el-tabs v-model="activeName" @tab-click="handleClick(form.id)">
          <el-tab-pane label="基础信息" name="baseInfo">
            <el-form ref="form" :model="form" label-width="120px" size="mini">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="医院名称：">{{ form.name }}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="医院等级：">
                    <dict-tag :options="dict.type.biz_hospital_level" :value="form.level"/>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="医院性质：">{{ form.nature }}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="医院特色：">{{ form.feature}}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="所在城市：">{{ form.province }}/{{ form.city }}/{{ form.district }}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="详细地址：">{{ form.address }}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="联系电话：">{{ form.contactPhone }}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="医院传真：">{{ form.fax }}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="成立时间：">{{ parseTime(form.setUpDate, '{y}-{m}-{d}') }}</el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="备注：">{{ form.remark }}</el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="简介" name="description">
            <el-button
              type="primary"
              style="margin-left: 85%"
              @click="handleEdit"
              v-hasPermi="['biz:hospital:edit']"
            >修改简介
            </el-button>
            <span v-html="form.description"></span>
          </el-tab-pane>
          <el-tab-pane label="科室" name="department">
            <el-form :model="departmentQueryParams" ref="departmentQueryForm" :inline="true" size="small"
                     v-show="showSearch" label-width="68px"
            >
              <el-form-item label="科室名称" prop="departmentName">
                <el-input
                  v-model="departmentQueryParams.departmentName"
                  placeholder="请输入科室名称"
                  clearable
                  @keyup.enter.native="handleDepartmentQuery"
                />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="departmentQueryParams.status" @change="handleDepartmentQuery">
                  <el-radio-button :label="undefined">全部</el-radio-button>
                  <el-radio-button label="active">启用</el-radio-button>
                  <el-radio-button label="inactive">禁用</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleDepartmentQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetDepartmentQuery">重置</el-button>
              </el-form-item>
            </el-form>
            <el-table v-loading="departmentLoading" :data="departmentList">
              <el-table-column label="序号" align="center" type="index"/>
              <el-table-column label="科室名称" align="center" prop="departmentName"/>
              <!--              <el-table-column label="科室简介" align="center" prop="departmentIntroduction">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <span v-html="scope.row.departmentIntroduction">{{scope.row.departmentIntroduction | ellipsisForDate}}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <span v-if="scope.row.status === 'active'" style="color: green">启用</span>
                  <span v-if="scope.row.status === 'inactive'" style="color: red">禁用</span>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="departmentTotal>0"
              :total="departmentTotal"
              :page.sync="departmentQueryParams.pageNum"
              :limit.sync="departmentQueryParams.pageSize"
              @pagination="getDepartmentList"
            />
          </el-tab-pane>
          <el-tab-pane label="医生" name="doctor">
            <el-form :model="doctorQueryParams" ref="doctorQueryForm" :inline="true" size="small" v-show="showSearch"
                     label-width="68px"
            >
              <el-form-item label="医生姓名" prop="doctorName">
                <el-input
                  v-model="doctorQueryParams.doctorName"
                  placeholder="请输入医生姓名"
                  clearable
                  @keyup.enter.native="handleDoctorQuery"
                />
              </el-form-item>
              <el-form-item label="科室名称" prop="departmentName">
                <el-input
                  v-model="doctorQueryParams.departmentName"
                  placeholder="请输入科室名称"
                  clearable
                  @keyup.enter.native="handleDoctorQuery"
                />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="doctorQueryParams.status" @change="handleDoctorQuery">
                  <el-radio-button :label="undefined">全部</el-radio-button>
                  <el-radio-button label="active">启用</el-radio-button>
                  <el-radio-button label="inactive">禁用</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleDoctorQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetDoctorQuery">重置</el-button>
              </el-form-item>
            </el-form>
            <el-table v-loading="doctorLoading" :data="doctorList">
              <el-table-column label="序号" align="center" type="index"/>
              <el-table-column label="医生名称" align="center" prop="doctorName"/>
              <el-table-column label="职级" align="center" prop="jobTitle">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.biz_doctor_title" :value="scope.row.jobTitle"/>
                </template>
              </el-table-column>
              <el-table-column label="所属科室" align="center" prop="departmentName"/>
              <el-table-column label="擅长" align="center" prop="goodAt" width="400px"/>
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <span v-if="scope.row.status === 'active'" style="color: green">启用</span>
                  <span v-if="scope.row.status === 'inactive'" style="color: red">禁用</span>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="doctorTotal>0"
              :total="doctorTotal"
              :page.sync="doctorQueryParams.pageNum"
              :limit.sync="doctorQueryParams.pageSize"
              @pagination="getDoctorList"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <el-image-viewer v-if="showViewer" :on-close="showViewerClose" :url-list="[guidePic]"></el-image-viewer>
  </div>
</template>

<script>
import { listHospital, getHospital, delHospital, addHospital, updateHospital, changeStatus } from '@/api/biz/hospital'
import { getAllDepartmentPageByHospital } from '@/api/biz/department'
import { listAllDoctorPageByHospital } from '@/api/biz/doctor'
import { getCityList } from '@/api/biz/city'
import { getToken } from '@/utils/auth'
import UEditor from '@/components/UEditor'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: 'Hospital',
  dicts: ['biz_hospital_level', 'biz_doctor_title'],
  components: {
    UEditor,
    ElImageViewer,
  },
  data() {
    let _this = this;
    return {
      zoom: 10,
      center: [120.585294, 31.299758],
      searchOption: {
        // 限制搜索城市的范围
        citylimit: false,
      },
      defaultValue: "",
      content: "",
      inputValue: "",
      searchResult: {
        address: "",
        latitude: "",
        longitude: "",
        name: "",
        type: "",
        country: "",
        province: "",
        city: "",
        area: "",
        township: "",
        street: "",
        neighborhood: "",
        locationName: "",
      },

      events: {
        click(e) {
          _this.center = [e.lnglat.lng, e.lnglat.lat];
          _this.form.lon = e.lnglat.lng;
          _this.form.lat = e.lnglat.lat;
          //_this.getAddress(_this.center);
          _this.defaultValue = "";
          console.log("defaultValue",_this.defaultValue);
        },
      },
      dialogVisible: false,
      dialogImageUrl: '',
      address:'',
      fileList:[],
      // 遮罩层
      loading: true,
      departmentLoading: true,
      doctorLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      departmentTotal: 0,
      doctorTotal: 0,
      // 医院表格数据
      hospitalList: [],
      departmentList: [],
      doctorList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        logo: undefined,
        level: undefined,
        feature: undefined,
        description: undefined,
        contactPhone: undefined,
        fax: undefined,
        province: undefined,
        provinceCode: undefined,
        city: undefined,
        cityCode: undefined,
        district: undefined,
        districtCode: undefined,
        address: undefined,
        setUpDate: undefined,
        status: undefined
      },
      departmentQueryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: undefined,
        departmentName: undefined,
        status: undefined
      },
      doctorQueryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: undefined,
        departmentName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      submitLoading: false,
      uploadSize:9,
      map:undefined,
      // 表单校验
      rules: {
        name: [
          { required: true, message: '医院名称不能为空', trigger: 'blur' }
        ],
        logo: [
          { required: true, message: '医院logo不能为空', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '医院等级不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        provinceCode: [
          { required: true, message: '省市区不能为空', trigger: 'blur' }
        ],
        nature: [
          { required: true, message: '医院性质不能为空', trigger: 'blur' }
        ],
        imageArr: [
          { required: true, message: "医院图片不能为空", trigger: "blur" }
        ],

      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/uploadObs'
      },
      // content: undefined,
      provinceList: [],
      province: '',
      cityList: [],
      city: [],
      districtList: [],
      district: '',
      showViewer: false,
      guidePic: '', // 预览图片的地址
      drawer: false,
      activeName: 'baseInfo',
      lnglat:''
    }
  },
  filters: {
    ellipsisForDate(value) {
      if (!value) return ''
      if (value.length > 10) {
        return value.slice(0, 10) + '...'
      }
      return value
    }
  },
  created() {
    this.getList()
    this.getCityList()
  },

  methods: {

    onSearchResult(pois) {
      console.log("pois",pois);
      //搜索
      let latSum = 0;
      let lngSum = 0;
      let that = this;
      if (pois && pois.length > 0) {
        //如果长度为1则无需转化
        let poi = pois[0];
        let lng = poi["lng"];
        let lat = poi["lat"];
        console.log("lng",lng);
        console.log("lat",lat);
        that.center = [lng, lat];
        that.zoom = 18;
        that.content = poi.name;
        that.searchResult.address = poi.address;
        that.searchResult.latitude = poi.lat;
        that.searchResult.longitude = poi.lng;

        that.form.longitude = lng;
        that.form.latitude = lat;

        //that.getAddress(that.center);
      } else {
        that.searchResult = [];
      }
    },
    // 获取详细地址
    // getAddress(center) {
    //   let _this = this;
    //   AMap.plugin("AMap.Geocoder",function(){
    //     let geocoder = new AMap.Geocoder({});
    //     geocoder.getAddress(center, function (status, result) {
    //       console.log("status",status);
    //       console.log("result",result);
    //       if (status === "complete" && result.info === "OK") {
    //         let obj = result.regeocode.addressComponent;
    //         let locationName =
    //           obj.province +
    //           obj.city +
    //           obj.district +
    //           obj.township +
    //           obj.street +
    //           obj.streetNumber;
    //         _this.form.address = locationName;
    //         console.log("_this.form.address",_this.form.address);
    //       }
    //     });
    //   })
    //
    // },

    /** 查询医院列表 */
    getList() {
      this.loading = true
      listHospital(this.queryParams).then(response => {
        this.hospitalList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /**查询医院下的科室列表*/
    getDepartmentList() {
      this.departmentLoading = true
      getAllDepartmentPageByHospital(this.departmentQueryParams).then(res => {
        this.departmentList = res.rows
        this.departmentTotal = res.total
        this.departmentLoading = false
      })
    },
    /**查询医院下的医生列表*/
    getDoctorList() {
      this.doctorLoading = true
      listAllDoctorPageByHospital(this.doctorQueryParams).then(res => {
        this.doctorList = res.rows
        this.doctorTotal = res.total
        this.doctorLoading = false
      })
    },
    // 取消按钮
    cancel() {
      this.fileList = [];
      this.open = false
      this.reset()
    },
    getIndex($index) {
      //表格序号
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        logo: null,
        level: null,
        feature: null,
        description: null,
        contactPhone: null,
        fax: null,
        province: null,
        provinceCode: null,
        city: null,
        cityCode: null,
        district: null,
        districtCode: null,
        address: null,
        setUpDate: null,
        status: 'active',
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        nature:null,
        imageArr:[],
        longitude:null,
        latitude:null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 搜索按钮操作 */
    handleDepartmentQuery() {
      this.departmentQueryParams.pageNum = 1
      this.getDepartmentList()
    },
    handleDoctorQuery() {
      this.doctorQueryParams.pageNum = 1
      this.getDoctorList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.cityCode = undefined
      this.queryParams.districtCode = undefined
      this.handleQuery()
    },
    resetDepartmentQuery() {
      this.resetForm('departmentQueryForm')
      this.handleDepartmentQuery()
    },
    resetDoctorQuery() {
      this.resetForm('doctorQueryForm')
      this.handleDoctorQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList = [];
      this.reset()
      this.open = true
      this.title = '添加医院'
      // this.$nextTick(() => {
      //   this.initMap();
      // });
    },
    handleChangeStatus(row) {
      let statusText = row.status === 'active' ? '禁用' : '启用'
      let status = row.status === 'active' ? 'inactive' : 'active'
      const ids = [row.id] || this.ids
      this.$confirm('是否确认' + statusText + '该项数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeStatus({ ids: ids, status: status })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(function() {
      })
    },
    handleBatchChangeStatus(status) {
      let statusText = status === 'active' ? '启用' : '禁用'
      const ids = this.ids
      this.$confirm('是否确认' + statusText + '选中的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeStatus({ ids: ids, status: status })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(function() {
      })
    },

    /**详情中启用禁用*/
    handleUpdateStatus(id, status) {
      let statusText = status === 'active' ? '禁用' : '启用'
      status = status === 'active' ? 'inactive' : 'active'
      const ids = [id] || this.ids
      this.$confirm('是否确认' + statusText + '该项数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeStatus({ ids: ids, status: status })
      }).then(() => {
        this.form.status = status
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(function() {
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.fileList = [];
      this.reset()
      const id = row.id || this.ids
      getHospital(id).then(response => {
        this.form = response.data
        this.form.provinceCode = parseInt(this.form.provinceCode)
        this.form.cityCode = parseInt(this.form.cityCode)
        this.form.districtCode = parseInt(this.form.districtCode)
        if (response.data.provinceCode && response.data.cityCode && response.data.districtCode) {
          this.showAddress(response.data.provinceCode, response.data.cityCode, response.data.districtCode)
        }
        this.form.imageArr = [];

        if(this.form.images){
          this.form.imageArr =  JSON.parse(this.form.images);
          for (let i = 0; i <this.form.imageArr.length ; i++) {
            this.fileList.push(
              {
                "url":this.form.imageArr[i]
              }
            )
          }
        }
        this.open = true
        this.title = '修改医院'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          console.log('form=', this.form)
          this.submitLoading = true
          if (this.form.id != null) {
            if (!this.form.cityCode || !this.form.districtCode || !this.form.provinceCode) {
              this.$modal.msgError('请完善省市区信息')
              return
            }
            updateHospital(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.submitLoading = false
              this.getList()
            }).catch(() => {
              this.submitLoading = false
            })
          } else {
            addHospital(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.submitLoading = false
              this.getList()
            }).catch(() => {
              this.submitLoading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除医院编号为"' + ids + '"的数据项？').then(function() {
        return delHospital(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('biz/hospital/export', {
        ...this.queryParams
      }, `hospital_${new Date().getTime()}.xlsx`)
    },
    /**详情*/
    goDetail(row) {
      this.activeName = 'baseInfo'
      getHospital(row.id).then(response => {
        this.form = response.data
        this.drawer = true
      })

    },
    /**详情中编辑*/
    handleEdit() {
      this.drawer = false
      this.form.provinceCode = parseInt(this.form.provinceCode)
      this.form.cityCode = parseInt(this.form.cityCode)
      this.form.districtCode = parseInt(this.form.districtCode)
      if (this.form.provinceCode && this.form.cityCode && this.form.districtCode) {
        this.showAddress(this.form.provinceCode, this.form.cityCode, this.form.districtCode)
      }
      this.open = true
      this.title = '修改医院'
    },

    handleAvatarSuccess(res, file) {
      this.form.logo = res.data.url
    },
    handleAvatarSuccess2(res, file,fileList) {
      console.log("fileList",fileList);
      this.form.imageArr.push(res.data.url);
      console.log("this.form.imageArr",this.form.imageArr);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    updateContent(content) {
      this.content = content
    },

    //获取省市区列表
    getCityList() {
      getCityList({ code: '' }).then(response => {
        this.provinceList = response.data
      })
    },
    initCity(code) {
      this.cityList = []
      this.districtList = []
      this.form.cityCode = undefined
      this.form.districtCode = undefined
      this.queryParams.cityCode = undefined
      this.queryParams.districtCode = undefined
      getCityList({ code: code }).then(response => {
        this.cityList = response.data
      })
      let o = this.provinceList.find((item) => {
        return item.id == code//比如：选项2
      })
      this.province = o.name
      this.form.province = this.province
    },
    initArea(code) {
      this.districtList = []
      this.form.districtCode = undefined
      this.queryParams.districtCode = undefined
      getCityList({ code: code }).then(response => {
        this.districtList = response.data
      })
      let o = this.cityList.find((item) => {
        return item.id == code//比如：选项2
      })
      this.form.cityCode = code
      this.city = o.name
      this.form.city = o.name
    },
    chooseArea(code) {
      let o = this.districtList.find((item) => {
        return item.id == code//比如：选项2
      })
      this.form.districtCode = code
      this.form.district = o.name
    },
    showAddress(provinceCode, cityCode, areaCode) {
      var o = this.provinceList.find((item) => {
        return item.id == provinceCode//比如：选项2
      })
      this.province = o.name
      getCityList({ code: provinceCode }).then(response => {
        this.cityList = response.data
        var o = this.cityList.find((item) => {
          return item.id == cityCode//比如：选项2
        })
        this.city = o.name
      })
      getCityList({ code: cityCode }).then(response => {
        this.districtList = response.data
        var o = this.districtList.find((item) => {
          return item.id == areaCode//比如：选项2
        })
        this.district = o.name
      })
      setTimeout(() => {
        // this.valueChange();
      }, 600)
    },
    view(url) {
      console.log('url', url)
      this.guidePic = url
      this.guidePic ? this.showViewer = true : this.$message.info('当前没有可预览的图片')
    },
    showViewerClose() {
      this.showViewer = false
    },
    handleClick(id) {
      if (this.activeName === 'baseInfo') {

      } else if (this.activeName === 'description') {

      } else if (this.activeName === 'department') {
        this.departmentQueryParams.hospitalId = id
        this.getDepartmentList()
      } else if (this.activeName === 'doctor') {
        this.doctorQueryParams.hospitalId = id
        this.getDoctorList()
      }
    },
    getPosition(data){
      this.form.longitude = data.lng;
      this.form.latitude = data.lat;
      console.log("this.form");
    },
    handlePictureCardPreview(file) {//预览
      console.log(file)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleError(err, file, fileList){//上传失败
      console.log(err)
    },
    handleUploadExceed(){
      this.$message.warning("最多上传:"+this.uploadSize + "张图片");
    },
    handleRemove(file, fileList) {//移除
      console.log("file", file);
      console.log("fileList", fileList);
      if(file.name){
        this.form.imageArr= this.form.imageArr.filter((x) => x !== file.response.data.url);
      }else {
        this.form.imageArr= this.form.imageArr.filter((x) => x !== file.url);
      }
    },
    closeDrawer(){
      this.fileList = [];
      this.open = false
      this.reset()
    },

  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.dd {
  width: 200px;
  float: left;
}

.level {
  margin-left: 17px;
  width: 80px;
  height: 35px;
  text-align: center;
  line-height: 35px;
  margin-top: 20px
}

.imageDiv {
  width: 150px;
  height: 100px;
  float: left;
  margin-left: 17px;
}

#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 600px;
}
</style>
